package org.ysh.demo.shiro;

//import org.apache.log4j.LogManager;
//import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.LoggerFactory;

public class IniShiroDemo {

//    private static final transient Logger log = LogManager.getLogger(IniShiroDemo.class);

    public static void main(String[] args) {

        System.out.println("基于INI文件的Shiro应用测试");

        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //获取SecurityManage实例
        SecurityManager securityManager = factory.getInstance();
//
//        SecurityManager instance2 = factory.getInstance();
//
//        System.out.println(instance2 == securityManager);
        SecurityUtils.setSecurityManager(securityManager);

        Subject currentUser = SecurityUtils.getSubject();

//        System.out.println(currentUser == null);

        // Do some stuff with a Session (no need for a web or EJB container!!!)
        Session session = currentUser.getSession();
        session.setAttribute("someKey", "aValue");
        String value = (String) session.getAttribute("someKey");
        if (value.equals("aValue")) {
            System.out.println("Retrieved the correct value! [" + value + "]");
        }

        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken("presidentskroob", "12345");
            token.setRememberMe(true);

//            currentUser.login(token);
            currentUser = securityManager.login(currentUser,token);
        }

        //say who they are:
        //print their identifying principal (in this case, a username):
        System.out.println("User [" + currentUser.getPrincipal() + "] logged in successfully.");

        System.out.println(currentUser.isRemembered());

        if(currentUser.hasRole("goodguy")) {
            System.out.println("拥有goodguy权限!");
        }else{
            System.out.println("不拥有goodguy权限");
        }

        if(currentUser.isPermitted("winnebago:drive:eagle5")){
            System.out.println("允许执行eagle5操作");
        }else{
            System.out.println("不允许执行操作!");
        }


        System.out.println(currentUser.getPrincipal());

        currentUser.logout();

    }
}
